package com.hs.telepass.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.hs.teleform.R;
import com.hs.telepass.controller.TaskController;
import com.hs.telepass.controller.VerifyPasswordTask;
import com.hs.telepass.controller.task.StartSingouSessionTask;
import com.hs.telepass.controller.task.UpdatePasswordTask;
import com.hs.telepass.manager.PreferencesManager;
import com.hs.telepass.manager.SingouManager;
import com.hs.telepass.model.json.response.StartResponseItemJson;
import com.hs.telepass.utils.StringUtil;
import com.hs.telepass.utils.ToastUtil;

public class SingouPasswordActivity extends BaseActivity {

    @InjectView(R.id.edtText_password)
    EditText mEdtTextPassword;
    @InjectView(R.id.edtText_new_password)
    EditText mEdtTextNewPassword;
    @InjectView(R.id.button_commit)
    Button mButtonCommit;
    @InjectView(R.id.btn_cancel)
    Button mBtnCancel;
    @InjectView(R.id.txtview_hostname)
    TextView mTxtviewHostname;

    public static final String EXTRA_HAS_SINGOU_PASSWORD = "extra_singou_password";
    public static final String EXTRA_IS_FROM_NEED_PSW_SWITCH = "extra_is_from_need_psw_switch";
    private Context mContext;
    private PreferencesManager mPreferencesManager;
    private String mSid;
    private String mRuntimeKey;
    private boolean mHasInitPsw;

    private boolean mIsFromPswSwitch;

    @OnClick(R.id.button_commit)
    void commit() {
        String password = mEdtTextPassword.getText().toString();
        String againPassword = mEdtTextNewPassword.getText().toString();


        if (StringUtil.isEmpty(password) || StringUtil.isEmpty(againPassword)) {
            ToastUtil.showMessageInShort(mContext, R.string.input_commit_empty);
        } else {

            if (!againPassword.equals(password)) {
                ToastUtil.showMessageInShort(mContext, R.string.input_user_password_not_same);
                return;
            }

            try {
                TaskController.getInstance().updatePassword(mContext, mSid, password, mRuntimeKey);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    @OnClick(R.id.btn_cancel)
    void backClick() {
        finish();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_singou_password);
        ButterKnife.inject(this);

        mContext = SingouPasswordActivity.this;
        mPreferencesManager = PreferencesManager.getInstance();

        mHasInitPsw = getIntent().getBooleanExtra(EXTRA_HAS_SINGOU_PASSWORD, false);
        mIsFromPswSwitch = getIntent().getBooleanExtra(EXTRA_IS_FROM_NEED_PSW_SWITCH, false);
        mSid = SingouManager.getInstance().getSid();
        //TODO runtieme 可优化?
        mRuntimeKey = SingouManager.getInstance().getRuntimeKey();

        if (mHasInitPsw) {
            mTxtviewHostname.setText(getString(R.string.title_update_password));
        } else {
            mTxtviewHostname.setText(getString(R.string.title_verify_password));
        }

        //TODO 优化start session
        if(StringUtil.isEmpty(mSid))
            tryStartSession();
    }

    private void tryStartSession(){
        try {
            String accountId = PreferencesManager.getInstance().getAccountId();
            try {
                SingouManager.getInstance().startSingouSession(accountId, mPreferencesManager.getPasswordKey(), mRuntimeKey, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UpdatePasswordTask.ACTION_UPDATE_PASSWORD_TASK);
        intentFilter.addAction(VerifyPasswordTask.ACTION_VERIFY_PASSWORD_TASK);
        intentFilter.addAction(StartSingouSessionTask.ACTION_START_FOR_PASSWORD_TASK);
        return intentFilter;
    }

    @Override
    public void handleOnReceive(Intent intent) {
        String action = intent.getAction();
        if (UpdatePasswordTask.ACTION_UPDATE_PASSWORD_TASK.equals(action)) {
            handleUpdatePassword(intent);
        } else if (VerifyPasswordTask.ACTION_VERIFY_PASSWORD_TASK.equals(action)) {
            handleVerifyPassword(intent);
        }else if(StartSingouSessionTask.ACTION_START_FOR_PASSWORD_TASK.equals(action)){
            handleInitPassword(intent);
        }
    }

    private void handleUpdatePassword(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:
                finish();
                break;
            case TaskController.EVENT_TASK_SUCCEED:
                PreferencesManager.getInstance().setPasswordKey(mEdtTextNewPassword.getText().toString());
                PreferencesManager.getInstance().setUserHasInitPsw(true);
                ToastUtil.showMessageInShort(mContext, R.string.edit_success);
                if(mIsFromPswSwitch){
                    setResult(Activity.RESULT_OK);
                }
                break;
            case TaskController.EVENT_TASK_FAILED:
                break;
            case TaskController.EVENT_TASK_ERROR:
                ToastUtil.showMessageInShort(mContext, R.string.edit_fail);
                break;
            default:
                break;
        }
    }

    private void handleVerifyPassword(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:
                finish();
                break;
            case TaskController.EVENT_TASK_SUCCEED:
                ToastUtil.showMessageInShort(mContext, R.string.edit_success);
                break;
            case TaskController.EVENT_TASK_FAILED:
                break;
            case TaskController.EVENT_TASK_ERROR:
                ToastUtil.showMessageInShort(mContext, R.string.edit_fail);
                break;
            default:
                break;
        }
    }

    private void handleInitPassword(Intent intent){
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:
                finish();
                break;
            case TaskController.EVENT_TASK_SUCCEED:
                StartResponseItemJson json = (StartResponseItemJson) intent.getSerializableExtra(TaskController.EXTRA_RESPONSE);
                mSid = json.getSid();
                break;
            case TaskController.EVENT_TASK_FAILED:
                break;
            case TaskController.EVENT_TASK_ERROR:
                ToastUtil.showMessageInShort(mContext, R.string.edit_fail);
                break;
            default:
                break;
        }
    }


    @Override
    public void finish() {
        super.finish();
//        this.overridePendingTransition(R.anim.activity_close,0);
    }


}